<script setup>
import DetailItem from '@/views/workOrder/components/DetailItem.vue'
import FileList from '@/components/FilePreviewer/FileList.vue'
import DisposeDetail from '@/views/dispose/index.vue'
import { useClipboardText } from '@/composables/useClipboardText.js'
import LevelTag from '@/views/workOrder/components/LevelTag.vue'
import { useOderDetail } from '@/composables/useOderDetail.js'
import { useRouter } from 'vue-router/composables'
import { useCommonTypesStore } from '@/stores/commonTypes.js'
import dayjs from 'dayjs'
import ConfirmDialog from '@/views/workOrder/components/ConfirmDialog.vue'
import { numUnitFormat } from '@/utils/unit.js'
import QuickReport from '@/views/workOrder/components/QuickReport.vue'
import { SentimentLevelList } from '@/common/index.js'
import { useOderDispose } from '@/composables/useOderDispose.js'
import { TimeLineProcessType } from '@/utils/config.js'
import ContentBox from '@/views/dispose/components/ContentBox.vue'
import { handleFileData } from '@/utils/helper.js'
import MLoading from '@/components/MLoading.vue'
const { processList, getOrderProcessData } = useOderDispose()
const { copyText } = useClipboardText()
const { state } = useCommonTypesStore()
const router = useRouter()
const {
  orderDetail,
  superviseTotal,
  getOrderDetailData,
  setDisposeOrderCancel,
  setPostSourceDelete,
  detailLoading
} = useOderDetail()
const activeName = ref('')
const detail = reactive({
  orderNo: '',
  auditId: '',
  show: false,
  backShow: false,
  quickShow: false,
  quickShow1: false,
  delShow: false,
  routerOrigin: '',
  refreshLoading: false
})
const subLabel = computed(() => {
  return SentimentLevelList.find(
    (item) => item.value === orderDetail.value.infoLevel
  )?.subLabel
})
const simpleInfo = computed(() => {
  return `${dayjs(orderDetail.value.publishTime).format('YYYYMMDD')} 【${
    subLabel.value
  }】
标题：${orderDetail.value.title}
内容：${orderDetail.value.content}
链接：${orderDetail.value.url ?? ''}
来源：${state.sourceTypeMap[orderDetail.value?.sourceType] ?? ''}
发帖人：${orderDetail.value?.author ?? ''} ${
    orderDetail.value?.fans ? '粉丝量（' + orderDetail.value?.fans + ')' : ''
  }
发布时间：${
    dayjs(orderDetail.value.publishTime).format('YYYY-MM-DD HH:mm') ?? ''
  }
传播情况：截止${dayjs(orderDetail.value.publishTime).format(
    'YYYY年MM月DD日'
  )},${
    orderDetail.value.forwardCount
      ? '转发' + orderDetail.value.forwardCount + '次,'
      : ''
  }${
    orderDetail.value.commentCount
      ? '评论' + orderDetail.value.commentCount + '次,'
      : ''
  }${
    orderDetail.value.thumbsCount
      ? '点赞' + orderDetail.value.thumbsCount + '次,'
      : ''
  } ${
    orderDetail.value.viewCount
      ? '阅读量' + orderDetail.value.viewCount + ','
      : ''
  }${
    orderDetail.value.newsForwardRemark
      ? orderDetail.value.newsForwardRemark + ', '
      : '无主流媒体关注报道, '
  } ${orderDetail.value.memo ?? ''}
`
})
const processNow = computed(() => processList.value[0])

onBeforeMount(async () => {
  detail.orderNo =
    router.currentRoute.query.orderNo || localStorage.getItem('currentOrderNo')
  detail.auditId = router.currentRoute.query.auditId
  detail.routerOrigin = router.currentRoute.meta.routerOrigin || ''
  localStorage.setItem('currentOrderNo', detail.orderNo)
  await initData()
})

// 加载数据
const initData = async () => {
  await getOrderDetailData(
    {
      orderNo: detail.orderNo,
      ...(detail.auditId ? { auditId: detail.auditId } : {})
    },
    async () => {
      await router.replace('/workOrder')
    }
  )
  await getOrderProcessData({
    orderNo: detail.orderNo
  })
  detail.refreshLoading = false
}

const goPage = (key) => {
  const page = {
    back: '/workOrder/report', // 上报
    distribute: '/workOrder/distribute', // 分发
    handle: '/dispose/input', // 处置
    addition: '/dispose/addition', // 补充处置记录
    audit: '/workOrder/inspect', // 上报审核
    checkResponse: '/workOrder/feedback', // 核查情况反馈
    superviseForm: '/supervise/input', // 督办
    disposePlan: '/dispose/plan', // 处置进度
    superviseList: '/supervise/list' // 督办列表
  }

  if (key === 'audit') {
    localStorage.setItem(
      'currentOrderBackNode',
      JSON.stringify(orderDetail.value?.backNode)
    )
    router.push({
      path: page[key],
      query: {
        orderNo: detail.orderNo,
        auditId: detail.auditId,
        routerOrigin: detail.routerOrigin
      }
    })
  } else {
    router.push({
      path: page[key],
      query: {
        orderNo: detail.orderNo,
        routerOrigin: detail.routerOrigin
      }
    })
  }
}

// 撤销工单
const cancelOrder = async () => {
  detail.show = false
  await setDisposeOrderCancel({
    orderNo: detail.orderNo
  })
}

// 发布人是否已经删除舆情
const publisherIsDelOrder = async (flag) => {
  if (flag) {
    // 已经删除舆情
    detail.delShow = false
    await setPostSourceDelete({
      orderNo: detail.orderNo,
      delete: '1'
    })
  } else {
    // 没有删除舆情
    detail.backShow = false
    await setPostSourceDelete({
      orderNo: detail.orderNo,
      delete: '0'
    })
  }
}

// 处理时长
const formattedTimespan = (timespan) => {
  const totalMinutes = Number(timespan)
  if (isNaN(totalMinutes)) {
    return ''
  }

  const days = Math.floor(totalMinutes / 1440)
  const remainingMinutesAfterDays = totalMinutes % 1440
  const hours = Math.floor(remainingMinutesAfterDays / 60)
  const minutes = remainingMinutesAfterDays % 60

  let result = ''

  if (days > 0) {
    result += `${days}天`
  }

  if (hours > 0 || days > 0) {
    result += `${hours}小时`
  }

  if (minutes > 0 || hours > 0 || days > 0) {
    result += `${minutes}分钟`
  }

  return result
}
// 判断所有属性是否为false
function allPropertiesNotTrue(obj) {
  for (let key in obj) {
    if (obj[key] === true) {
      return false
    }
  }
  return true
}

const isShowTabBar = computed(() => {
  return (
    activeName.value === 'order' &&
    orderDetail.value.id &&
    (!allPropertiesNotTrue(orderDetail.value?.operation) ||
      router.currentRoute.query.auditId)
  )
})
// 打开生成速报弹窗
const handleQuickReport = () => {
  detail.quickShow = true
}
</script>

<template>
  <div class="box-border h-full overflow-x-hidden overflow-y-auto bg-#F5F7FA">
    <MLoading v-if="!detail.refreshLoading" :show.sync="detailLoading" />
    <van-pull-refresh v-model="detail.refreshLoading" @refresh="initData">
      <!--  头部信息  -->
      <div class="p-12px bg-#36b274">
        <!--   状态 -->
        <div class="bg-#FFFFFF rounded-4px overflow-hidden relative">
          <div class="px-12px pt-20px pb-17px box-border text-#54565C">
            <h3 class="m-0 text-20px font-600 leading-28px c-#1E2226">
              {{ state.workerOrderStatusMap?.[orderDetail?.status] }}
            </h3>
            <template v-if="processNow">
              <p class="text-16px font-400 leading-20px mt-2px mb-16px">
                舆情工单{{ TimeLineProcessType[processNow?.type] }}
              </p>
              <DetailItem
                v-if="processNow?.status !== 'WAIT'"
                :label="processNow?.type !== 'RESPONSE' ? '处理时间' : '响应时间'"
                :content="
                  processNow?.updateTime
                    ? dayjs(processNow?.updateTime).format('YYYY-MM-DD HH:mm:ss')
                    : ''
                "
                py="2px"
              />
              <DetailItem
                :label="processNow?.type !== 'RESPONSE' ? '处理单位' : '响应单位'"
                :content="processNow.orgName"
                py="2px"
              />
              <DetailItem
                v-if="
                  processNow?.status !== 'WAIT' && processNow?.type !== 'RESPONSE'
                "
                label="处理内容"
                py="2px"
              >
                <ContentBox
                  :content="processNow.content"
                  :at-org-obj="processNow?.atOrgObj"
                  :timeout-days="processNow.timeoutDays"
                  text-hidden
                />
              </DetailItem>
            </template>
            <div
              class="pt-12px flex items-center"
              @click="goPage('disposePlan')"
            >
              <span class="text-14px font-400 leading-20px">
                查看全部处置进度
              </span>
              <img
                alt=""
                class="box-border w-10px h-14px"
                src="@/assets/img/icon_MoreArrow.svg"
              />
            </div>
          </div>
          <div
            class="bg-#F2F3F5 h-36px px-11px flex items-center justify-start"
          >
            <img
              alt=""
              class="box-border w-14px h-14px"
              src="@/assets/img/icon_time-black.svg"
            />
            <span class="pl-4px text-#1E2226 text-14px font-500 leading-20px">
              处理时长
              {{ formattedTimespan(orderDetail.timespan) }}
            </span>
          </div>
        </div>
        <!--   督办消息 -->
        <div
          v-if="superviseTotal > 0"
          class="box-border mt-8px h-36px rounded-4px bg-#FFF0F0 px-12px flex items-center justify-between"
          @click="goPage('superviseList')"
        >
          <div class="flex items-center justify-start">
            <i class="inline-block w-6px h-6px bg-#FA6D5D rounded-50%" />
            <span class="pl-4px text-#1E2226 text-14px font-400 leading-20px">
              该舆情工单有 {{ superviseTotal }} 条督办消息
            </span>
          </div>
          <img
            alt=""
            class="box-border w-12px h-12px rotate--90"
            src="@/assets/img/icon_requestListArrow.svg"
          />
        </div>
      </div>
      <!--  tab切换-->
      <div class="w-full bg-white">
        <van-tabs
          v-model="activeName"
          class="custom-tabs m-b12px z-99 flex justify-center"
          color="#229F60"
          title-active-color="#229F60"
          title-inactive-color="#1E2226"
        >
          <van-tab
            name="order"
            title="舆情信息"
            title-class="w-120px text-16px font-500 leading-22px text-#1E2226 h-40px"
            title-style="flex:none;"
          ></van-tab>
          <van-tab
            name="dispose"
            title="处置情况"
            title-class="w-120px text-16px font-500 leading-22px text-#1E2226 h-40px"
            title-style="flex:none;"
          ></van-tab>
        </van-tabs>
      </div>
      <!-- 舆情信息 -->
      <div v-if="activeName === 'order'" class="p-12px pb-84px">
        <div
          :class="{
            new: orderDetail.newOld === 1,
            old: orderDetail.newOld === 2
          }"
          class="detail-card bg-white rounded-4px p-12px mb-12px"
        >
          <detail-item
            :content="state.infoTypeMap[orderDetail?.infoType]"
            label="舆情类别"
          >
            <div class="flex items-center justify-between">
              <span>{{ state.infoTypeMap[orderDetail?.infoType] || '--' }}</span>
              <div
                v-if="orderDetail?.infoType"
                class="c-#229F60 ml-8px text-16px font-500 leading-22px w-auto flex items-center justify-center"
                @click="handleQuickReport"
              >
                <img
                  class="w-20px h-20px"
                  src="@/assets/img/icon_note.svg"
                  alt=""
                />
                <span>生成速报</span>
              </div>
            </div>
          </detail-item>
          <detail-item
            :content="state.sourceTypeMap[orderDetail?.sourceType]"
            label="舆情来源"
          />
          <detail-item label="舆情级别">
            <LevelTag
              v-if="orderDetail?.infoLevel"
              :level="orderDetail?.infoLevel"
            />
          </detail-item>
          <detail-item
            :content="orderDetail?.memo ? orderDetail?.memo : '--'"
            label="热搜或热度情况描述"
            top
          />
          <detail-item
            v-if="orderDetail?.newsForwardRemark"
            :content="orderDetail?.newsForwardRemark"
            label="主流新闻媒体关注转发情况"
            top
          />
        </div>
        <div class="bg-white rounded-4px p-12px mb-12px">
          <detail-item label="发布人">
            <div>{{ orderDetail?.author }}</div>
            <div
              class="flex h-auto w-auto"
              v-if="orderDetail?.author && !orderDetail?.sourceDeleted"
            >
              <span
                @click="detail.delShow = true"
                class="select-none active:bg-[#229F6099] bg-[#229f60ff] text-12px py-4px px-6px text-white rounded-4px font-400 leading-12px"
              >
                发布人已删除
              </span>
            </div>
            <div
              class="flex"
              v-if="orderDetail?.author && orderDetail?.sourceDeleted === true"
            >
              <span
                class="mr-4px text-12px font-400 leading-12px text-#71747A inline-block p-4px rounded-2px bg-#F2F3F5"
              >
                发布人已删除
              </span>
              <div
                class="c-#229F60 ml-8px text-14px font-500 leading-20px w-auto flex items-center justify-center"
                @click="detail.backShow = true"
              >
                <img
                  class="w-20px h-20px"
                  src="@/assets/img/icon_record.svg"
                  alt=""
                />
                <span>撤销</span>
              </div>
            </div>
          </detail-item>
          <detail-item
            :content="
              orderDetail.publishTime
                ? dayjs(orderDetail.publishTime).format('YYYY-MM-DD HH:mm')
                : '--'
            "
            label="发布时间"
          />
          <detail-item :content="orderDetail?.fans ? orderDetail?.fans : '--'">
            <template #label>
              <span>发布人<br />粉丝量:</span>
            </template>
          </detail-item>
          <detail-item
            :content="orderDetail?.title ? orderDetail?.title : '--'"
            label="舆情标题"
          />
          <detail-item
            :content="orderDetail?.content ? orderDetail?.content : '--'"
            label="舆情内容"
          />
          <detail-item label="原文链接">
            <template>
              <span class="mr-4px">{{
                orderDetail?.url ? orderDetail?.url : '--'
              }}</span>
              <span
                v-if="orderDetail?.url"
                class="whitespace-nowrap text-14px font-600 leading-14px text-#229F60"
                @click="copyText(orderDetail?.url, '链接复制成功^_^')"
                >复制链接</span
              >
            </template>
          </detail-item>
          <detail-item v-if="orderDetail?.attachment?.length" label="附件">
            <FileList
              :files="handleFileData(orderDetail?.attachment)"
              :preview="true"
              :upload="false"
            />
          </detail-item>
          <div class="bg-#F8F9FC rounded-4px px-8px py-12px grid grid-cols-3">
            <span class="text-13px mb-8px font-400 leading-18px text-#71747A">
              转发量&nbsp;{{ numUnitFormat(orderDetail?.forwardCount) || 0 }}
            </span>
            <span class="text-13px mb-8px font-400 leading-18px text-#71747A">
              点赞量&nbsp;{{ numUnitFormat(orderDetail?.thumbsCount) || 0 }}
            </span>
            <span class="text-13px mb-8px font-400 leading-18px text-#71747A">
              播放量&nbsp;{{ numUnitFormat(orderDetail?.plyCount) || 0 }}
            </span>
            <span class="text-13px mb-8px font-400 leading-18px text-#71747A">
              评论量&nbsp;{{ numUnitFormat(orderDetail?.commentCount) || 0 }}
            </span>
            <span class="text-13px mb-8px font-400 leading-18px text-#71747A">
              阅读量&nbsp;{{ numUnitFormat(orderDetail?.viewCount) || 0 }}
            </span>
          </div>
        </div>
        <!-- 工单情况 -->
        <div class="bg-white rounded-4px p-12px mb-12px">
          <detail-item label="工单号">
            <template>
              <span class="mr-4px">{{ orderDetail?.orderNo }}</span>
              <span
                v-if="orderDetail?.orderNo"
                class="text-16px font-500 leading-22px text-#229F60"
                @click="copyText(orderDetail?.orderNo, '工单号复制成功^_^')"
              >
                复制
              </span>
            </template>
          </detail-item>
          <detail-item :content="orderDetail?.createOrgName" label="录入单位" />
          <detail-item
            :content="
              orderDetail.createTime
                ? dayjs(orderDetail.createTime).format('YYYY-MM-DD HH:mm')
                : '--'
            "
            label="工单时间"
          />
          <detail-item
            :content="
              orderDetail?.self !== null
                ? orderDetail?.self === 1
                  ? '本单位'
                  : '分发'
                : '--'
            "
            label="工单来源"
          />
        </div>
      </div>
      <!-- 处置情况 -->
      <div v-if="activeName === 'dispose'" class="">
        <DisposeDetail :order-no="detail.orderNo" />
      </div>
    </van-pull-refresh>
    <!--底部工具栏-->
    <div
      v-if="isShowTabBar"
      class="shadow-[0_0_16px_0_rgba(0,0,0,0.05)] fixed bottom-0 left-0 w-full"
    >
      <div
        class="flex w-full justify-between px-16px pt-12px pb-20px bg-white box-border"
      >
        <!--左边-->
        <div class="h-full">
          <template v-if="orderDetail?.operation?.cancel">
            <div
              class="flex flex-col items-center justify-center"
              @click="detail.show = true"
            >
              <img
                alt=""
                class="box-border w-18px h-18px mb-6px"
                src="@/assets/img/icon_upload.svg"
              />
              <span class="text-12px font-400 leading-12px">撤销</span>
            </div>
          </template>
          <template v-if="orderDetail?.operation?.back">
            <div
              class="flex flex-col items-center justify-center"
              @click="goPage('back')"
            >
              <img
                alt=""
                class="box-border w-18px h-18px mb-6px"
                src="@/assets/img/icon_upload.svg"
              />
              <span class="text-12px font-400 leading-12px">上报</span>
            </div>
          </template>
        </div>
        <!--右边-->
        <div class="flex items-center justify-end gap-10px">
          <van-button
            v-if="orderDetail?.operation?.distribute"
            class="w-115px h-40px"
            plain
            type="primary"
            @click="goPage('distribute')"
          >
            分发
          </van-button>
          <van-button
            v-if="orderDetail?.operation?.handle"
            class="w-135px h-40px"
            plain
            type="primary"
            @click="goPage('handle')"
          >
            处置
          </van-button>
          <van-button
            v-if="orderDetail?.operation?.addition"
            class="w-135px h-40px"
            plain
            type="primary"
            @click="goPage('addition')"
          >
            补充处置记录
          </van-button>
          <van-button
            v-if="router.currentRoute.query.auditId && orderDetail?.backNode"
            class="w-96px h-40px"
            type="primary"
            @click="goPage('audit')"
          >
            上报审核
          </van-button>
          <van-button
            v-if="orderDetail?.operation?.supervise"
            class="h-40px"
            :class="
              orderDetail?.operation?.checkResponse ? 'w-96px' : 'w-135px'
            "
            :plain="!orderDetail?.operation?.handle"
            type="primary"
            @click="goPage('superviseForm')"
          >
            督办
          </van-button>
          <van-button
            v-if="orderDetail?.operation?.checkResponse"
            class="h-40px"
            :class="
              orderDetail?.operation?.distribute ||
              orderDetail?.operation?.supervise
                ? 'w-130px'
                : 'w-200px'
            "
            type="primary"
            @click="goPage('checkResponse')"
          >
            核查情况反馈
          </van-button>
        </div>
      </div>
    </div>
    <ConfirmDialog
      :show.sync="detail.show"
      confirm-name="撤销"
      message="是否撤销该工单？"
      @confirm="cancelOrder"
    />
    <ConfirmDialog
      :show.sync="detail.delShow"
      confirm-name="确定"
      message="是否发布人已删除舆情？"
      @confirm="publisherIsDelOrder(true)"
    />
    <ConfirmDialog
      :show.sync="detail.backShow"
      confirm-name="确定"
      message="确定撤销吗？"
      @confirm="publisherIsDelOrder(false)"
    />
    <QuickReport :show.sync="detail.quickShow" :text="simpleInfo" />
  </div>
</template>

<style lang="less" scoped>
.detail-card {
  position: relative;

  &::before {
    display: block;
    position: absolute;
    left: 0;
    top: -3.2vw;
    width: 12.533vw;
    height: 6.4vw;
  }

  &.new::before {
    content: '';
    background: url('@/assets/img/icon_label-new.svg') no-repeat center center;
    background-size: 100% 100%;
  }

  &.old::before {
    content: '';
    background: url('@/assets/img/icon_label-old.svg') no-repeat center center;
    background-size: 100% 100%;
  }
}

.van-button--primary {
  font-size: 16px;
  line-height: 16px;
  font-weight: 500;
  color: #fff;
  background-color: #36b374;
  border: 1px solid #36b374;
  border-radius: 4px;
  white-space: nowrap;
}

.van-button--plain.van-button--primary {
  color: #07c160;
}

.van-button--plain {
  background-color: #fff;
}

.custom-tabs::v-deep(.van-tab__text.van-tab__text--ellipsis) {
  font-size: 4.264vw;
}

.custom-tabs::v-deep(.van-tabs__line) {
  bottom: 5.5vw;
}
</style>
